from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from app.core.deps import get_current_active_user
from app.db.database import get_db
from app.models.homepage import Homepage
from app.schemas.homepage import HomepageCreate, HomepageUpdate, Homepage as HomepageSchema

router = APIRouter()

@router.get("/", response_model=List[HomepageSchema])
def get_homepages(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取首屏版本列表"""
    homepages = db.query(Homepage).order_by(Homepage.version.desc()).offset(skip).limit(limit).all()
    return homepages

@router.get("/published", response_model=HomepageSchema)
def get_published_homepage(db: Session = Depends(get_db)):
    """获取已发布的首屏内容"""
    homepage = db.query(Homepage).filter(Homepage.is_published == True).first()
    if homepage is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="No published homepage found"
        )
    return homepage

@router.post("/", response_model=HomepageSchema)
def create_homepage(
    homepage: HomepageCreate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """创建新版本的首屏内容"""
    # 获取最新版本号
    latest_version = db.query(Homepage).order_by(Homepage.version.desc()).first()
    new_version = (latest_version.version + 1) if latest_version else 1
    
    db_homepage = Homepage(
        **homepage.dict(),
        version=new_version,
        created_by=current_user.id
    )
    db.add(db_homepage)
    db.commit()
    db.refresh(db_homepage)
    return db_homepage

@router.get("/{homepage_id}", response_model=HomepageSchema)
def get_homepage(homepage_id: int, db: Session = Depends(get_db)):
    """获取特定版本的首屏内容"""
    homepage = db.query(Homepage).filter(Homepage.id == homepage_id).first()
    if homepage is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Homepage not found"
        )
    return homepage

@router.put("/{homepage_id}", response_model=HomepageSchema)
def update_homepage(
    homepage_id: int,
    homepage: HomepageUpdate,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """更新首屏内容"""
    db_homepage = db.query(Homepage).filter(Homepage.id == homepage_id).first()
    if db_homepage is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Homepage not found"
        )
    
    update_data = homepage.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_homepage, field, value)
    
    db.commit()
    db.refresh(db_homepage)
    return db_homepage

@router.post("/{homepage_id}/publish")
def publish_homepage(
    homepage_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """发布首屏版本"""
    # 取消所有已发布的版本
    db.query(Homepage).filter(Homepage.is_published == True).update({"is_published": False})
    
    # 发布指定版本
    db_homepage = db.query(Homepage).filter(Homepage.id == homepage_id).first()
    if db_homepage is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Homepage not found"
        )
    
    db_homepage.is_published = True
    db.commit()
    db.refresh(db_homepage)
    return {"message": "Homepage published successfully", "homepage": db_homepage}

@router.delete("/{homepage_id}")
def delete_homepage(
    homepage_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """删除首屏版本"""
    db_homepage = db.query(Homepage).filter(Homepage.id == homepage_id).first()
    if db_homepage is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Homepage not found"
        )
    
    # 不允许删除已发布的版本
    if db_homepage.is_published:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Cannot delete published homepage"
        )
    
    db.delete(db_homepage)
    db.commit()
    return {"message": "Homepage deleted successfully"} 